package org.footballmanager.pandafootball.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.common.exception.ExceptionEnum;
import org.footballmanager.pandafootball.common.exception.MyException;
import org.footballmanager.pandafootball.common.util.DateFormatUtil;
import org.footballmanager.pandafootball.common.util.ExportExcelSpecial;
import org.footballmanager.pandafootball.common.util.RandomNumber;
import org.footballmanager.pandafootball.system.dao.FootPersonDao;
import org.footballmanager.pandafootball.system.domain.*;
import org.footballmanager.pandafootball.system.form.impl.FootPersonSearchForm;
import org.footballmanager.pandafootball.system.form.impl.FootPersonSkillSearchForm;
import org.footballmanager.pandafootball.system.mapper.FootPersonMapper;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class FootPersonServiceImpl extends ServiceImpl<FootPerson> implements FootPersonService {
    @Autowired
    private FootPersonDao footPersonDao;
    @Autowired
    private FootPersonMapper footPersonMapper;
    @Autowired
    private FootUserPersonService footUserPersonService;
    @Autowired
    private PhotoService photoService;
    @Autowired
    private FootUserService footUserService;
    @Autowired
    private FootClubService footClubService;
    @Autowired
    private FootQdService footQdService;
    @Autowired
    private FootSkillService footSkillService;
    @Autowired
    private FootGjService footGjService;
    @Autowired
    private FootWzService footWzService;
    @Autowired
    private FootAreaService footAreaService;
    @Autowired
    private FootPersonSkillService footPersonSkillService;
    @Autowired
    private FootTableTitleService footTableTitleService;
    @Autowired
    private FootSslsService footSslsService;
    @Autowired
    private FootXfService footXfService;
    @Autowired
    private FootGpService footGpService;
    @Autowired
    private FootDjService footDjService;
    @Autowired
    private RedisService redisService;

    /**
     * 删除球员记录
     *
     * @param id      主键
     * @param request 请求
     * @return 是否成功
     */
    @Override
    @Transactional
    public int delete(Serializable id, HttpServletRequest request) {
        FootPerson t = this.get(id);
        log.info("删除球员:" + t.toString());
        //删除球员的实体图片
        if (t.getZp() != null) {
            photoService.delete(t.getZp(), request);
        }
        return super.delete(id, request);
    }

    /**
     * 删除所有球员
     *
     * @param request 请求
     */
    @Override
    public void deleteAll(HttpServletRequest request) {
        List<FootPerson> list = footPersonDao.selectAll();
        if (list != null && !list.isEmpty()) {
            for (FootPerson person : list) {
                super.delete(person.getId(), request);
            }
        }
    }

    /**
     * 导出球员信息
     *
     * @param path    路径
     * @param request 请求
     */
    @Override
    public void getExcel(byte[] path, HttpServletRequest request) throws IOException {
        footUserService.cancelLogin(true, request);
        List<FootDj> djList = footDjService.findBySort();
        //获取Excel文档的路径
        HSSFWorkbook wookbook = new HSSFWorkbook(new ByteArrayInputStream(path));
        HSSFSheet sheet = wookbook.getSheetAt(0);
        int rows = sheet.getPhysicalNumberOfRows();
        Date date = new Date();
        for (int i = 1; i < rows; i++) {
            HSSFRow row = sheet.getRow(i);
            if (row == null) {
                break;
            }
            int cells = row.getLastCellNum();
            StringBuilder value = new StringBuilder();
            processValue(value, cells, row);
            if (value.length() <= 0) {
                break;
            }
            String values = value.deleteCharAt(value.length() - 1).toString();
            String[] val = values.split(Constants.COMMA);
            if (val.length <= 0) {
                break;
            }
            processPerson(val, date, djList, request);
        }
        deleteNotUse(date, request);
        footUserService.cancelLogin(false, request);
    }

    /**
     * 处理球员信息
     *
     * @param val     读取的excel字符串
     * @param date    日期
     * @param djList  等级列表
     * @param request 请求
     */
    private void processPerson(String[] val, Date date, List<FootDj> djList, HttpServletRequest request) {
        FootPerson fp = this.findByQybm(val[0].trim());
        if (null == fp) {
            fp = new FootPerson();
            fp.setQybm(val[0].trim());
            fp.setWz(1L);
            this.save(fp, request);
        }
        this.setUpdateValue(fp, val, date, djList, request);
    }

    /**
     * 删除没有用的球员
     *
     * @param date    日期
     * @param request 请求
     */
    private void deleteNotUse(Date date, HttpServletRequest request) {
        List<FootPerson> list = this.getall();
        if (list != null && !list.isEmpty()) {
            for (FootPerson footPerson : list) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (footPerson.getUpdateDate() == null || !sdf.format(footPerson.getUpdateDate()).equals(sdf.format(date))) {
                    FootPersonSkillSearchForm footPersonSkillSearchForm = new FootPersonSkillSearchForm();
                    footPersonSkillSearchForm.setQyId(footPerson.getId());
                    footPersonSkillService.deleteAll(footPersonSkillSearchForm, request);
                    this.deleteForReal(footPerson.getId());
                    //从所有的球队里删掉没有的球员
                    footUserPersonService.deletePersonByQyid(footPerson.getId());
                    //解约里删掉
                    footXfService.deletePersonByQyid(footPerson.getId());
                    //挂牌里删掉
                    footGpService.deletePersonByQyid(footPerson.getId());
                }
            }
        }
    }

    /**
     * 设置更新值
     *
     * @param fp      球员实体类
     * @param val     值数组
     * @param date    日期
     * @param request 请求
     */
    private void setUpdateValue(FootPerson fp, String[] val, Date date, List<FootDj> djList, HttpServletRequest request) {
        fp.setYw(val[1].trim());
        fp.setHm(val[2] == null || "".equals(val[2]) ? null : Integer.parseInt(val[2].trim()));
        if (val[3] != null && !"自由球员".equals(val[3])) {
            FootQd qd = footQdService.findByName(val[3].trim());
            FootSsls ssls = footSslsService.findByName(val[4].trim());
            if (ssls == null) {
                ssls = new FootSsls();
                ssls.setName(val[4].trim());
                footSslsService.save(ssls, null);
            }
            if (qd == null) {
                qd = new FootQd();
                qd.setQdmc(val[3].trim());
                qd.setSslsId(ssls.getId());
                footQdService.save(qd, null);
            } else {
                qd.setSslsId(ssls.getId());
                footQdService.updateNotNull(qd, null);
            }
            fp.setSsjlb(qd.getId());
        }

        FootGj gj = footGjService.findByName(val[5].trim());
        FootArea area = footAreaService.findByName(val[6]);
        if (area == null) {
            area = new FootArea();
            area.setName(val[6].trim());
            footAreaService.save(area, null);
        }
        if (gj == null) {
            gj = new FootGj();
            gj.setName(val[5]);
            gj.setAreaId(area.getId());
            footGjService.save(gj, null);
        } else {
            gj.setAreaId(area.getId());
            footGjService.updateNotNull(gj, null);
        }
        fp.setGj(gj.getId());
        fp.setSg(val[7] == null ? null : Integer.parseInt(val[7].trim()));
        fp.setTz(val[8] == null ? null : Integer.parseInt(val[8].trim()));
        fp.setNl(val[9] == null ? null : Integer.parseInt(val[9].trim()));
        fp.setGyj(val[10].trim());
        fp.setWz(footWzService.findByWzbm(val[11].trim()));
        fp.setPosition(val[12].trim().replace(";", ","));
        processSkills(fp, val);
        fp.setPf(null == val[39] ? 0 : Integer.parseInt(val[39].trim()));
        fp.setPCard(val[40].trim().replace(";", ","));
        fp.setSCard(val[41].trim().replace(";", ","));
        fp.setCom(val[42].trim().replace(";", ","));
        fp.setOther(val[43].trim().replace(";", ","));

        if (djList != null && !djList.isEmpty()) {
            for (FootDj dj : djList) {
                if (fp.getPf() >= dj.getPfFrom() && fp.getPf() < dj.getPfTo()) {
                    fp.setDjId(dj.getId());
                }
            }
        }
        fp.setUpdateDate(date);
        super.updateNotNull(fp, request);
    }

    /**
     * 处理球员技能
     *
     * @param fp  球员实体类
     * @param val excel读取信息
     */
    private void processSkills(FootPerson fp, String[] val) {
        //13-38
        List<FootSkill> skills = footSkillService.getall();
        for (int i = 0; i < skills.size(); i++) {
            FootSkill skill = skills.get(i);
            FootPersonSkill footPersonSkill = new FootPersonSkill();
            footPersonSkill.setSkillId(skill.getId());
            footPersonSkill.setQyId(fp.getId());
            if (val.length > (i + 13) && val[i + 13] != null) {
                footPersonSkill.setNumber(Integer.parseInt(val[i + 13].trim()));
            }
            footPersonSkillService.save(footPersonSkill, null);
        }
    }

    /**
     * 导入SCard技能信息
     *
     * @param path    路径
     * @param request 请求
     */
    @Override
    public void getSCardExcel(byte[] path, HttpServletRequest request) throws IOException {
        //获取Excel文档的路径
        // 创建对Excel工作簿文件的引用
        HSSFWorkbook wookbook = new HSSFWorkbook(new ByteArrayInputStream(path));
        // 在Excel文档中,第一张工作表的缺省索引是0
        // 其语句为:HSSFSheet sheet = wookbook.getSheet("Sheet1")
        HSSFSheet sheet = wookbook.getSheetAt(0);
        //获取到Excel文件中的所有行数
        int rows = sheet.getPhysicalNumberOfRows();
        //遍历行
        for (int i = 1; i < rows; i++) {
            // 读取左上端单元格
            HSSFRow row = sheet.getRow(i);
            // 行不为空
            if (row == null) {
                return;
            }
            //获取到Excel文件中的所有的列
            int cells = 61;
            StringBuilder value = new StringBuilder();
            processValue(value, cells, row);
            //将数据插入到mysql数据库中
            String values = value.deleteCharAt(value.length() - 1).toString();
            String[] val = values.split(Constants.COMMA);
            if (val.length <= 0) {
                return;
            }
            FootPerson fp = this.findByQybm(val[0].trim());
            if (null != fp) {
                fp.setSCard(val[1]);
                this.updateNotNull(fp, request);
            }
        }
    }

    /**
     * 导入PCard技能信息
     *
     * @param path    路径
     * @param request 请求
     */
    @Override
    public void getPCardExcel(byte[] path, HttpServletRequest request) throws IOException {
        //获取Excel文档的路径
        // 创建对Excel工作簿文件的引用
        HSSFWorkbook wookbook = new HSSFWorkbook(new ByteArrayInputStream(path));
        // 在Excel文档中,第一张工作表的缺省索引是0
        // 其语句为:HSSFSheet sheet = wookbook.getSheet("Sheet1")
        HSSFSheet sheet = wookbook.getSheetAt(0);
        //获取到Excel文件中的所有行数
        int rows = sheet.getPhysicalNumberOfRows();
        //遍历行
        for (int i = 1; i < rows; i++) {
            // 读取左上端单元格
            HSSFRow row = sheet.getRow(i);
            // 行不为空
            if (row == null) {
                return;
            }
            //获取到Excel文件中的所有的列
            int cells = 61;
            StringBuilder value = new StringBuilder();
            processValue(value, cells, row);
            //将数据插入到mysql数据库中
            String values = value.deleteCharAt(value.length() - 1).toString();
            String[] val = values.split(Constants.COMMA);
            if (val.length <= 0) {
                return;
            }
            FootPerson fp = this.findByQybm(val[0].trim());
            if (null != fp) {
                fp.setPCard(val[1]);
                this.updateNotNull(fp, request);
            }
        }
    }

    /**
     * 处理值
     *
     * @param value 值
     * @param cells 行
     * @param row   列
     */
    private void processValue(StringBuilder value, int cells, HSSFRow row) {
        //遍历列
        for (int j = 0; j < cells; j++) {
            //获取到列的值
            HSSFCell cell = row.getCell(j);
            if (cell != null) {
                switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_FORMULA:
                        value.append(Constants.COMMA);
                        break;
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        value.append(Double.valueOf(cell.getNumericCellValue()).intValue());
                        value.append(Constants.COMMA);
                        break;
                    case HSSFCell.CELL_TYPE_STRING:
                        value.append(cell.getStringCellValue());
                        value.append(Constants.COMMA);
                        break;
                    default:
                        value.append(Constants.COMMA);
                        break;
                }
            } else {
                value.append(Constants.COMMA);
            }
        }
    }

    /**
     * 找到所有对应球员
     *
     * @param from    评分从
     * @param to      评分到
     * @param userId  用户主键
     * @param request 请求
     * @return 球员名称
     */
    @Override
    public FootPerson findPersonByScore(String from, String to, Long userId, HttpServletRequest request) {
        Example example = new Example(FootPerson.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andGreaterThanOrEqualTo("pf", from);
        if (null != to && !"".equals(to)) {
            criteria.andLessThanOrEqualTo("pf", to);
        }
        criteria.andEqualTo("delFlag", 0);
        List<FootPerson> list = this.findall(example);
        if (list != null && !list.isEmpty()) {
            Random rand = new Random();
            int number = rand.nextInt(list.size() - 1);
            FootPerson fp = list.get(number);
            //保存球员到用户球员表中
            footUserPersonService.saveUserPerson(userId, fp, request);
            return fp;
        }
        return null;
    }

    /**
     * 根据名称查询记录
     *
     * @param name 球员名称
     * @return 球员记录
     */
    @Override
    public FootPerson findByName(String name) {
        Example example = new Example(FootPerson.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name", name);
        criteria.andEqualTo("delFlag", 0);
        return this.findByExample(example);
    }

    /**
     * 翻页方法
     *
     * @param footPersonSearchForm 条件
     * @return 列表
     */
    @Override
    public List<FootPerson> findall(FootPersonSearchForm footPersonSearchForm) {
        List<FootPerson> list;
        if (!StringUtils.isEmpty(footPersonSearchForm.getNlName1()) || !StringUtils.isEmpty(footPersonSearchForm.getNlName2())
                || !StringUtils.isEmpty(footPersonSearchForm.getNlName3()) || !StringUtils.isEmpty(footPersonSearchForm.getNlName4())) {
            list = footPersonMapper.findallWithParam(footPersonSearchForm);
            if (list != null && !list.isEmpty()) {
                for (FootPerson footPerson : list) {
                    footPerson.setSkillList(footPersonMapper.getSkills(footPerson.getId()));
                    footPerson.setMap(list2Map(footPerson.getSkillList()));
                }
            }
        } else {
            list = footPersonMapper.findall(footPersonSearchForm);
        }
        if (list != null && !list.isEmpty()) {
            for (FootPerson p : list) {
                p.setColor(footDjService.findColorByPf(p.getPf()));
            }
        }
        return list;
    }

    /**
     * 列表2转Map
     *
     * @param list 技能列表
     * @return 转换成的Map
     */
    private Map<String, Integer> list2Map(List<FootPersonSkill> list) {
        Map<String, Integer> map = new HashMap<>();
        if (list != null) {
            for (FootPersonSkill footPersonSkill : list) {
                map.put(footPersonSkill.getYw(), footPersonSkill.getNumber());
            }
        }
        return map;
    }

    /**
     * 根据球员编码查找球员
     *
     * @param qybm 球员编码
     * @return 球员信息
     */
    @Override
    public FootPerson findByQybm(String qybm) {
        Example example = new Example(FootPerson.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("qybm", qybm.trim());
        criteria.andEqualTo("delFlag", 0);
        return this.findByExample(example);
    }

    /**
     * 根据主键获取记录
     *
     * @param id 主键
     * @return 记录
     */
    @Override
    public FootPerson get(Serializable id) {
        FootPerson person = footPersonMapper.findById(id);
        person.setSkillList(footPersonMapper.getSkills(person.getId()));
        person.setMap(list2Map(person.getSkillList()));
        return person;
    }

    /**
     * 根据等级主键获取球员列表
     *
     * @param djId 等级主键
     * @return 球员列表
     */
    @Override
    public List<FootPerson> findByDjId(Long djId) {
        return footPersonMapper.findByDjId(djId);
    }

    /**
     * 查询
     *
     * @param entityname           实体类名
     * @param map                  参数
     * @param footPersonSearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, FootPersonSearchForm footPersonSearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), footPersonSearchForm);
        Page<FootPerson> page = PageHelper.startPage(footPersonSearchForm.getPageIndex(), footPersonSearchForm.getPageSize());
        List<FootPerson> list = this.findall(footPersonSearchForm);
        map.addAttribute(Constants.PI, page.toPageInfo());
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }

    /**
     * 初始化
     *
     * @param entityname           实体类名
     * @param footPersonSearchForm 条件
     * @param map                  参数
     */
    @Override
    public void init(String entityname, FootPersonSearchForm footPersonSearchForm, Model map) {
        map.addAttribute("wzList", redisService.get("listwz"));
        map.addAttribute("djList", redisService.get("listdj"));
        map.addAttribute("userList", footUserService.getall());
        map.addAttribute("gjList", redisService.get("listgj"));
        map.addAttribute("qdList", footQdService.getall());
        map.addAttribute("clubList", footClubService.getall());
        map.addAttribute("nlList", footSkillService.getall());
        map.addAttribute("head", footTableTitleService.findByTableName(Constants.PERSONTABLE));
        FootPersonSearchForm newFootPersonSearchForm = new FootPersonSearchForm();
        if (footPersonSearchForm != null) {
            newFootPersonSearchForm = footPersonSearchForm;
        }
        map.addAttribute(String.format(Constants.FORMNAME, entityname), newFootPersonSearchForm);
    }

    /**
     * 删除所有
     *
     * @param footPersonSearchForm 条件
     * @param request              请求
     */
    @Override
    public void deleteAll(FootPersonSearchForm footPersonSearchForm, HttpServletRequest request) {
        if (footPersonSearchForm.getSelectIds() != null) {
            String[] result = footPersonSearchForm.getSelectIds().split(Constants.COMMA);
            for (String id : result) {
                this.delete(Long.parseLong(id), request);
            }
        }
    }

    /**
     * 导出
     *
     * @param request  请求
     * @param response 响应
     */
    @Override
    public void exprot(HttpServletRequest request, HttpServletResponse response) {
        try {
            String title = "球员信息表";
            String ExcelName = String.format("%s-%s.xlsx", title, DateFormatUtil.getFullDate());
            Workbook wb = ExportExcelSpecial.createWorkbook();
            Sheet sheet = wb.createSheet("Export");
            sheet.setDefaultColumnWidth(15);
            sheet.setDefaultRowHeight((short) 400);
            CellStyle style = ExportExcelSpecial.getCellStyle(wb);
            int rownum = 0;
            //通过tableName获取表格字段
            List<FootTableTitle> list = footTableTitleService.findListByTableName("foot_person");
            ExportExcelSpecial.addHeader(sheet.createRow(rownum++), ExportExcelSpecial.getTitleStyle(wb), list);
            FootPersonSearchForm footPersonSearchForm = new FootPersonSearchForm();
            List<FootPerson> personList = footPersonMapper.findall(footPersonSearchForm);
            if (personList == null || personList.isEmpty()) {
                return;
            }
            for (FootPerson footPerson : personList) {
                int col = 0;
                Row rowTotal = sheet.createRow(rownum++);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getQybm(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getName(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getSsjlb(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getYw(), style);
                FootGj gj = footGjService.get(footPerson.getGj());
                ExportExcelSpecial.addCell(rowTotal, col++, gj != null ? gj.getName() : null, style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getTz(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getSr(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getWz(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getSg(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getHm(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getNl(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getGrjj(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getZyjx(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getPf(), style);
                FootDj dj = footDjService.get(footPerson.getDjId());
                ExportExcelSpecial.addCell(rowTotal, col++, dj != null ? dj.getQydj() : null, style);
                ExportExcelSpecial.addCell(rowTotal, col++, dj != null ? dj.getQysj() : null, style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getZp(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getGyj(), style);
                List<FootPersonSkill> skillList = footPersonSkillService.findByQyid(footPerson.getId());
                if (skillList != null && !skillList.isEmpty()) {
                    for (FootPersonSkill skill : skillList) {
                        ExportExcelSpecial.addCell(rowTotal, col++, skill.getNumber(), style);
                    }
                }
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getPCard(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getSCard(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getCom(), style);
                ExportExcelSpecial.addCell(rowTotal, col++, footPerson.getPosition(), style);
                ExportExcelSpecial.addCell(rowTotal, col, footPerson.getOther(), style);
            }
            response.setContentType("application/vnd.ms-excel");
            ServletOutputStream out = ExportExcelSpecial.getResponseOutputStream(ExcelName, request, response);
            ExportExcelSpecial.writer(wb, out);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(ExceptionEnum.OUTPUTEXCEPTION, e);
        }
    }

    /**
     * 更新数据
     *
     * @param id      主键
     * @param ssjlb   球队主键
     * @param sr      生日
     * @param grjj    个人简介
     * @param zyjx    重要奖项
     * @param hm      还没
     * @param request 请求
     * @return Json返回值
     */
    @Override
    public JsonReturn edit(Long id, Long ssjlb, Date sr, String grjj, String zyjx, Integer hm, HttpServletRequest request) {
        if (id == null) {
            return new JsonReturn(Constants.ERROR);
        }
        FootPerson person = this.get(id);
        if (person == null) {
            return new JsonReturn(Constants.ERROR);
        }
        person.setHm(hm);
        if (sr != null) {
            person.setSr(sr);
            person.setNl(DateFormatUtil.getAgeByBirth(sr));
        }
        person.setSsjlb(footQdService.get(ssjlb).getId());
        person.setGrjj(grjj);
        person.setZyjx(zyjx);
        this.updateNotNull(person, request);
        return new JsonReturn(Constants.OK);
    }

    /**
     * 非物理删除
     *
     * @param id 主键
     */
    @Override
    public void deleteForReal(Long id) {
        FootPerson p = footPersonDao.selectByPrimaryKey(id);
        //log.info("删除球员:" + p.toString());
        //删除球员的实体图片
        if (p.getZp() != null) {
            photoService.delete(p.getZp(), null);
        }
        footPersonDao.deleteByPrimaryKey(id);
    }

    /**
     * 重新计算等级
     */
    @Override
    public void resetDj() {
        List<FootPerson> list = this.getall();
        List<FootDj> djList = footDjService.findBySort();
        if (list != null && !list.isEmpty()) {
            for (FootPerson fp : list) {
                if (djList != null && !djList.isEmpty()) {
                    for (FootDj dj : djList) {
                        if (fp.getPf() >= dj.getPfFrom() && fp.getPf() < dj.getPfTo()) {
                            fp.setDjId(dj.getId());
                            this.updateNotNull(fp, null);
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据机率获取球员
     *
     *
     * @param userId 用户主键
     * @param reward  机率设置类
     * @param request 请求
     * @return 球员信息
     */
    @Override
    public FootPerson findQyByOdds(Long userId, FootReward reward, HttpServletRequest request) {
        String qydj = RandomNumber.randomGetPerson(reward);
        FootDj dj = footDjService.findByQydj(qydj);
        return findPersonByScore(dj.getPfFrom().toString(), dj.getPfTo().toString(), userId, request);
    }

    /**
     * 根据djId获取球员
     *
     * @param userId  用户主键
     * @param djId    等级主键
     * @param request 请求
     * @return 球员信息
     */
    @Override
    public FootPerson getDjQy(Long userId, Long djId, HttpServletRequest request) {
        FootDj dj = footDjService.get(djId);
        return findPersonByScore(dj.getPfFrom().toString(), dj.getPfTo().toString(), userId, request);
    }
}
